import Taro, { getCurrentInstance } from "@tarojs/taro";
import { envConfig } from "./config/index";
import {
  getCompanyInfo,
  getDetaultCardId,
  getCardDetail,
  getVerifiedStatus,
  getDynamicBadge,
  sendBrowsEvent,
} from "../service/data";
import updateMiniProgram from "./updateMiniProgram";
import { runHeartbeatSend } from "./heartbeat";
import { login } from "./login";
import { COMPANYINFO, COMPANYBASE, HEADERHEIGTHT, HEADERTITLE,SYSTRMINFO } from "../constants/company";
import { CARDID, CARDDETAIL, ENTRANCETYPE } from "../constants/card";
import configStore from "../store/index";
import formatEntranceOptions from "./formatEntranceOptions";
import PATH_MAP, {
  HOME_PATH,
  isTabPage,
  isCardPage,
  isDependCard,
} from "./pathMap";
import {
  AUTHORIZEPHONESTATUS,
  FORWARDUSERID,
  ISVERIFIED,
  ALLINITCOMPLTET
} from "../constants/userInfo";
import { getAuthorizePhone } from "./getPhoneNumber";
import { listenIMAccountStatus, createIMUser, IMAddFriend,getInvalidCardList } from "./im/IM_Init";
import checkWorkHandover from "./workHandover";
import { setFromShareId } from './forward/shareId'

let cardId = null;
const store = configStore();
//  初始化请求数据
async function initData() {
  const { params: options } = getCurrentInstance().router;
  const pathTemp = getCurrentInstance().router.path;
  const router = pathTemp.substring(pathTemp.length, 0);
  await updateMiniProgram(); // 检查小程序更新
  await listenMemoryWarning(); // 检测手机内存
  await runHeartbeatSend(); // 发送心跳
  await __getSystminfo(); // 获取手机系统信息
  await __getCompanyInfo(); // 获取企业信息
  await login(); // 登录
  await getInvalidCardList() // 
  const _options = await formatEntranceOptions(options, router);
  await __setForwardUserId(_options);

  await __updateEntranceModal(_options, router);
  await __getCardId(_options.cardId); // 获取默认名片及名片详情
  await __checkCardId(router); // 检查路由
  await __getVerifiedStatus(); // 获取身份认证状态
  await __getCardDetail(); // 获取名片详情
  await __updateTabPage(router); // 更新tab
  await __getAuthorizePhone(); // 获取手机号授权状态
  await createIMUser(); // 创建IM
  await __listenIMAccountStatus(_options); // 监听im状态
  await __checkWorkHandover(options); // 检查工作交接
  await __updateShareStatus(); // 更新分享状态
  await __reportBrowsEvent(_options); // 发送获客海报浏览事件
  await __setFromShareId(_options.routeId || null)// 初始化shareId
}

// 获取企业配置
async function __getCompanyInfo() {
  const __companyInfo = Taro.getStorageSync("v2_company");
  if (__companyInfo) {
    handleStore(COMPANYINFO, __companyInfo);
    handleStore(COMPANYBASE, __companyInfo.companyBase);
  } else {
    const res = await getCompanyInfo();
    Taro.setStorageSync("v2_company", res);
    handleStore(COMPANYINFO, res);
    handleStore(COMPANYBASE, res.companyBase);
  }
}
// 获取手机信息
async function __getSystminfo() {
  const headerHeight = 44;
  const s = Taro.getSystemInfoSync();
  handleStore(SYSTRMINFO, s);
  handleStore(HEADERHEIGTHT, s.statusBarHeight + headerHeight);
}

async function listenMemoryWarning() {
  if (!Taro.onMemoryWarning) return;
  Taro.onMemoryWarning((res) => {
    console.log("运行内存不足", res);
    // showToast('运行内存不足')
  });
}
// 设置转发人信息
async function __setForwardUserId(_options) {
  const isEntrance = "sourceType" in _options;
  if (isEntrance) {
    // 存储转发人信息 用于分销等
    const sourceType = +_options.sourceType;
    if (sourceType === 1 || sourceType === 4) {
      handleStore(FORWARDUSERID, _options.forwardUserId || null);
    }
  }
}
// 设置入口页 是否弹出 及 弹窗模式
function __updateEntranceModal(options, router) {
  const qrCodeType = +options.qrCodeType;

  // __entranceType
  // 1 => 普通登录弹窗
  // 2 => 名片弹窗
  // 3 => 问答弹窗

  // qrCodeType值：
  // -1   => 名片分发
  // 0    => 名片二维码
  // 1    => 雷达名片海报二维码
  // 2    => 雷达鸡血海报二维码
  // 3    => 优惠券二维码
  // 4    => 小程序商品海报二维码
  // 5    => 小程序名片海报二维码
  // 6    => 纸质名片二维码
  // 7    => 获客海报
  // 8    => 动态海报
  // 9    => 企管商城
  // 10   => 产品手册
  // 11   => 门店扫名片码
  // 11   => 公文包
  // 12   => 核销

  // 是否显示获客海报问答弹窗 qrCodeType === 7 且 wordPosterQaText 有内容
  if ([7].includes(qrCodeType) && options.wordPosterQaText) {
    handleStore(ENTRANCETYPE, 3);
    return;
  }

  if (!store.__userInfo) return;

  // 是否显示收下名片弹窗
  let isScan = false;
  if (Taro.getLaunchOptionsSync) {
    const option = Taro.getLaunchOptionsSync();
    isScan = option.scene === 1047;
  }
  // 通过扫码 并且未授权过用户信息 在名片页弹出收下名片弹窗
  if (
    isScan &&
    !store.userInfo.isAuthUserInfo &&
    [-1, 0, 1, 2, 5, 6, 7, 11].includes(qrCodeType) &&
    isCardPage(router)
  ) {
    Taro.hideTabBar();
    handleStore(ENTRANCETYPE, 2);
  }
}
// 获取名片
async function __getCardId(options) {
  if (options && options.cardId) {
    cardId = options.cardId;
    handleStore(CARDID, options.cardId);
  } else {
    await __getDetaultCardId(options);
  }
}
// 检查路由,没有名片的时候去名片列表页
async function __checkCardId(router) {
  if (!cardId && isDependCard(router)) {
    Taro.reLaunch({
      url: HOME_PATH,
    });
  }
}
// 获取默认名片
async function __getDetaultCardId(options) {
  const r = await getDetaultCardId({
    sourceType: (options && options.sourceType) || 0,
  });
  cardId = r.cardId;
  handleStore(CARDID, r.cardId);
}
// 获取名片详情
async function __getCardDetail() {
  const cardTemp = getStoreData("card");
  if (cardTemp && cardTemp.__cardId) {
    const res = await getCardDetail({ cardId: cardTemp.__cardId });
    let c = JSON.parse(JSON.stringify(res));
    c = { ...c, cardId: cardTemp.__cardId };
    handleStore(CARDDETAIL, c);
  }
}
// 更新tabbar
async function __updateTabPage(router) {
  const c = getStoreData("company");
  const { navigateConfigVO } = c.__companyInfo;
  await updateHeaderTitle(router,navigateConfigVO)
  await __updateTabBar(navigateConfigVO);
  await __setDynamicTabbarBadge(navigateConfigVO);
}

async function updateHeaderTitle(router,navigateConfigVO){
  if (!isTabPage(router)) return;
  if (!navigateConfigVO) return;
  const { navFooter } = navigateConfigVO;
  const index = PATH_MAP[router].tabIndex;
  handleStore(HEADERTITLE, navFooter[index] ? navFooter[index].name : "");
}

// 更新tabbar
async function __updateTabBar(n) {
  const { navFooter } = n;
  // 设置TABBAR名称&图标
  navFooter.forEach(({ name, icon, selectIcon }, index) => {
    Taro.setTabBarItem({
      index, // 暂时去掉动态TAB
      text: name,
      iconPath: `${envConfig.host}gov/icon/${icon}`,
      selectedIconPath: `${envConfig.host}gov/icon/${selectIcon}`,
      success: () => {},
      fail: () => {},
    });
  });
}
// 设置动态的角标
async function __setDynamicTabbarBadge(n) {
  const { cardDefaultStyle } = getStoreData("card").__cardDetail;
  if (cardDefaultStyle === 1) return;
  const { navFooter } = n;
  // 以防没有动态tabbar
  if (Taro.getCurrentPages()[0].route === "pages/tabbar/dynamic/dynamic")
    return;
  if (navFooter.length === 5) {
    const res = await getDynamicBadge({
      accessCardId: cardId,
    });
    if (res && +res > 0) {
      Taro.setTabBarBadge({
        index: 2,
        text: res,
        success: () => {},
        fail: () => {},
      });
    }
  }
}
// 获取手机号授权状态
async function __getAuthorizePhone() {
  const a = await getAuthorizePhone();
  handleStore(AUTHORIZEPHONESTATUS, a);
}

// 监听im用户状态并添加好友
async function __listenIMAccountStatus(options) {
  listenIMAccountStatus()
    .then(() => {
      IMAddFriend(cardId, options);
    })
    .catch(() => {});
}
// 获取身份认证状态
async function __getVerifiedStatus() {
  if (!cardId) return;
  const isVerified = Taro.getStorageSync("isVerified");
  if (isVerified) {
    handleStore(ISVERIFIED, isVerified);
    return;
  }
  const r = await getVerifiedStatus({ browseCardId: cardId });
  if (r.authentication === 1) {
    Taro.setStorageSync("isVerified", 1);
    handleStore(ISVERIFIED, isVerified);
  }
}
async function __checkWorkHandover(options) {
  const c = getStoreData("card");
  if (c.__cardDetail && c.__cardDetail.handoverCardId) {
    checkWorkHandover(c.__cardDetail, cardId, options);
  }
}
// 更新分享状态
async function __updateShareStatus() {
  const c = getStoreData("card");
  const com = getStoreData("company");
  if (!c.__cardDetail) return;

  const { expireStatus } = com.__companyBase;
  const { cardForwardStatus } = c.__cardDetail;
  if (expireStatus === 2 || cardForwardStatus === 1) {
    Taro.hideShareMenu();
  }
}
// 发送获客海报浏览事件
async function __reportBrowsEvent(options) {
  // eslint-disable-next-line no-shadow
  const { cardId, posterId, posterSrc, actionType, parentId } = options;
  if (!posterSrc) return;
  const formData = {
    cardId,
    actionId: posterSrc,
    actionType: actionType || 2,
    shareId: posterId,
  };
  if (parentId) formData.parentActionId = parentId;
  await sendBrowsEvent(formData);
}
// 设置分享id
async function __setFromShareId(routeId){
  setFromShareId(routeId)
}
// 保存数据到状态管理里
function handleStore(type, payload) {
  store.dispatch({
    type,
    payload,
  });
}
// 获取store中的值
function getStoreData(type) {
  return store.getState()[type];
}
export { initData, store, handleStore, getStoreData,updateHeaderTitle };
